const { observable, action, runInAction } = require('mobx-miniprogram');
const cloudHelper = require('../../../helpers/cloud_helper');
const dataHelper = require('../../../helpers/data_helper');
const dayjs = require('dayjs');

// 资源状态描述映射
const STATUS_DESC = {
    1: '草稿',
    2: '已发布',
    3: '生产版本',
    4: '客户确认版本',
    5: '已废弃'
};

// 模拟资料分类数据
function getMockCategories() {
    return [
        {
            id: 'pcb',
            title: 'PCB设计文件',
            desc: '电路板设计文件',
            icon: 'icon-file-pcb'
        },
        {
            id: 'bom',
            title: 'BOM清单',
            desc: '物料清单',
            icon: 'icon-file-bom'
        },
        {
            id: 'schematic',
            title: '原理图',
            desc: '电路原理图',
            icon: 'icon-file-schematic'
        },
        {
            id: 'doc',
            title: '技术文档',
            desc: '包含包装指引、加工指引等文档',
            icon: 'icon-file-doc'
        },
        {
            id: 'software',
            title: '软件资料',
            desc: '代码、烧录文件等',
            icon: 'icon-file-code'
        },
        {
            id: 'datasheet',
            title: '元器件规格书',
            desc: '元器件技术规格说明',
            icon: 'icon-file-datasheet'
        }
    ];
}

// 资料管理Store
const materialStore = observable({
    // 资源列表
    materialList: [],
    
    // 资料分类列表
    materialCategories: [],
    
    // 是否需要刷新
    needRefresh: false,
    
    // 加载状态
    isLoading: false,
    
    // 是否已加载全部
    isAllLoaded: false,
    
    // 分页数据
    page: 1,
    pageSize: 20,
    
    // 搜索和筛选条件
    searchKey: '',
    currentCateId: '',
    currentStatus: 0,
    sortType: '',
    sortVal: '',
    
    // 筛选器是否打开
    isFilterOpen: false,
    
    // 快速访问列表
    quickAccessList: [],
    
    // 错误状态
    loadingError: false,
    errorMsg: '',

    // 获取资料分类
    fetchMaterialCategories: action(async function() {
        try {
            // 调用云函数获取资料分类
            const res = await cloudHelper.callCloudData('material/category', {});
            
            if (!res || !res.data) {
                const mockData = getMockCategories();
                runInAction(() => {
                    this.materialCategories = mockData;
                });
                return mockData;
            }
            
            runInAction(() => {
                this.materialCategories = res.data;
                this.needRefresh = false;
            });
            return res.data;
        } catch (err) {
            console.error('获取资料分类失败', err);
            // 如果云函数调用失败，使用模拟数据
            const mockData = getMockCategories();
            runInAction(() => {
                this.materialCategories = mockData;
            });
            return mockData;
        }
    }),
    
    // 获取资源列表
    fetchMaterialList: action(async function(forceRefresh = false) {
        try {
            // 如果正在加载，则返回
            if (this.isLoading) return;
            
            runInAction(() => {
                this.isLoading = true;
            });
            
            // 已全部加载且非强制刷新时，直接返回
            if (this.isAllLoaded && !forceRefresh) {
                runInAction(() => {
                    this.isLoading = false;
                });
                return;
            }
            
            // 强制刷新或首页时清空列表
            if (forceRefresh || this.page === 1) {
                runInAction(() => {
                    this.materialList = [];
                    this.page = 1;
                    this.isAllLoaded = false;
                });
            }
            
            // 构建请求参数
            const params = {
                page: this.page,
                size: this.pageSize
            };
            
            // 添加筛选条件
            if (this.searchKey) {
                params.search = this.searchKey;
            }
            
            if (this.currentCateId) {
                params.cateId = this.currentCateId;
            }
            
            if (this.currentStatus > 0) {
                params.status = this.currentStatus;
            }
            
            if (this.sortType) {
                params.sortType = this.sortType;
                params.sortVal = this.sortVal || 'desc';
            }
            
            // 调用云函数获取资源列表
            const res = await cloudHelper.callCloudData('material/list', params);
            
            // 模拟数据
            if (!res || !res.data) {
                const mockData = this.getMockMaterials();
                
                runInAction(() => {
                    this.materialList = this.page === 1 ? mockData : [...this.materialList, ...mockData];
                    this.isAllLoaded = this.page >= 3; // 最多3页模拟数据
                    this.isLoading = false;
                    this.loadingError = false;
                    this.errorMsg = '';
                    this.page++;
                });
                
                return;
            }
            
            const list = res.data.list || [];
            const total = res.data.total || 0;
            
            // 处理数据
            const materials = list.map(item => ({
                ...item,
                statusDesc: STATUS_DESC[item.status] || '未知状态',
                time: item.updateTime ? dayjs(item.updateTime).format('YYYY-MM-DD HH:mm') : '',
                createTimeDesc: item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm') : '',
                isExpanded: false // 默认不展开
            }));
            
            runInAction(() => {
                this.materialList = this.page === 1 ? materials : [...this.materialList, ...materials];
                this.isAllLoaded = this.materialList.length >= total;
                this.isLoading = false;
                this.loadingError = false;
                this.errorMsg = '';
                this.page++;
            });
            
        } catch (err) {
            console.error('获取资源列表失败', err);
            
            runInAction(() => {
                this.isLoading = false;
                this.loadingError = true;
                this.errorMsg = '获取资源列表失败，请重试';
            });
            
            // 如果是首页或强制刷新，使用模拟数据
            if (this.page === 1 || forceRefresh) {
                const mockData = this.getMockMaterials();
                runInAction(() => {
                    this.materialList = mockData;
                    this.loadingError = false;
                });
            }
        }
    }),
    
    // 搜索资源
    searchMaterials: action(function(key) {
        this.searchKey = key;
        this.page = 1;
        this.isAllLoaded = false;
        return this.fetchMaterialList(true);
    }),
    
    // 设置分类筛选
    setCateFilter: action(function(cateId) {
        this.currentCateId = cateId;
        this.page = 1;
        this.isAllLoaded = false;
        return this.fetchMaterialList(true);
    }),
    
    // 设置状态筛选
    setStatusFilter: action(function(status) {
        this.currentStatus = status;
        this.page = 1;
        this.isAllLoaded = false;
        return this.fetchMaterialList(true);
    }),
    
    // 设置排序
    setSorting: action(function(type, val = 'desc') {
        if (this.sortType === type && this.sortVal === val) {
            // 如果点击的是当前排序字段，切换排序方向
            this.sortVal = val === 'asc' ? 'desc' : 'asc';
        } else {
            this.sortType = type;
            this.sortVal = val;
        }
        
        this.page = 1;
        this.isAllLoaded = false;
        return this.fetchMaterialList(true);
    }),
    
    // 切换筛选器显示
    toggleFilter: action(function() {
        this.isFilterOpen = !this.isFilterOpen;
    }),
    
    // 切换资源展开状态
    toggleExpand: action(function(resourceId) {
        const updatedList = this.materialList.map(item => {
            if (item.id === resourceId) {
                return {
                    ...item,
                    isExpanded: !item.isExpanded
                };
            }
            return item;
        });
        
        this.materialList = updatedList;
    }),
    
    // 添加到快速访问
    addToQuickAccess: action(function(resource) {
        // 检查是否已在快速访问列表
        const exists = this.quickAccessList.some(item => item.id === resource.id);
        if (exists) return false;
        
        // 添加到列表并保存到本地存储
        const quickItem = {
            id: resource.id,
            title: resource.title,
            version: resource.version,
            cateId: resource.cateId,
            status: resource.status
        };
        
        this.quickAccessList = [...this.quickAccessList, quickItem];
        this.saveQuickAccessList();
        
        return true;
    }),
    
    // 从快速访问移除
    removeFromQuickAccess: action(function(resourceId) {
        this.quickAccessList = this.quickAccessList.filter(item => item.id !== resourceId);
        this.saveQuickAccessList();
    }),
    
    // 保存快速访问列表到本地存储
    saveQuickAccessList: function() {
        try {
            wx.setStorageSync('MATERIAL_QUICK_ACCESS', this.quickAccessList);
        } catch (e) {
            console.error('保存快速访问列表失败', e);
        }
    },
    
    // 加载快速访问列表
    loadQuickAccessList: action(function() {
        try {
            const data = wx.getStorageSync('MATERIAL_QUICK_ACCESS');
            if (data) {
                this.quickAccessList = data;
            }
        } catch (e) {
            console.error('加载快速访问列表失败', e);
            this.quickAccessList = [];
        }
    }),
    
    // 设置需要刷新
    setNeedRefresh: action(function(value = true) {
        this.needRefresh = value;
    }),
    
    // 获取模拟资源数据
    getMockMaterials: function() {
        const statuses = [1, 2, 3, 4, 5];
        const cateIds = ['pcb', 'bom', 'schematic', 'doc', 'software', 'datasheet'];
        const result = [];
        
        for (let i = 0; i < 15; i++) {
            const status = statuses[Math.floor(Math.random() * statuses.length)];
            const cateId = this.currentCateId || cateIds[Math.floor(Math.random() * cateIds.length)];
            const cateName = this.getCateName(cateId);
            
            // 模拟依赖数据
            const dependencies = [];
            const depCount = Math.floor(Math.random() * 4); // 0-3个依赖
            for (let j = 0; j < depCount; j++) {
                const depCateId = cateIds[Math.floor(Math.random() * cateIds.length)];
                dependencies.push({
                    id: `mock_dep_${i}_${j}`,
                    title: `${this.getCateName(depCateId)}依赖文件${j+1}`,
                    version: `1.${j}.0`,
                    cateId: depCateId
                });
            }
            
            result.push({
                id: `mock_material_${i}`,
                title: `${cateName}资料 ${i + 1}`,
                desc: `这是一个${cateName}资料的示例描述，包含了相关的技术细节和使用说明。`,
                version: `1.${i % 10}.${Math.floor(i / 10)}`,
                status,
                statusDesc: STATUS_DESC[status],
                cateId,
                cateName,
                time: dayjs().subtract(i % 30, 'day').format('YYYY-MM-DD HH:mm'),
                createTimeDesc: dayjs().subtract(i % 30 + 15, 'day').format('YYYY-MM-DD HH:mm'),
                creator: `用户${i % 5 + 1}`,
                fileSize: `${(Math.random() * 10).toFixed(2)}MB`,
                isExpanded: false,
                dependencies
            });
        }
        
        // 如果有搜索条件，进行过滤
        if (this.searchKey) {
            return result.filter(item => 
                item.title.includes(this.searchKey) || 
                item.desc.includes(this.searchKey)
            );
        }
        
        // 如果有分类筛选
        if (this.currentCateId) {
            return result.filter(item => item.cateId === this.currentCateId);
        }
        
        // 如果有状态筛选
        if (this.currentStatus > 0) {
            return result.filter(item => item.status === this.currentStatus);
        }
        
        return result;
    },
    
    // 根据分类ID获取分类名称
    getCateName: function(cateId) {
        const cateMap = {
            'pcb': 'PCB',
            'bom': 'BOM',
            'schematic': '原理图',
            'doc': '文档',
            'software': '软件',
            'datasheet': '规格书'
        };
        
        return cateMap[cateId] || '未知';
    }
});

module.exports = {
    materialStore
}; 